package cn.wolfcode.orderServer.service.impl;

import cn.wolfcode.orderServer.domain.Order;
import cn.wolfcode.orderServer.feign.ProductFeignApi;
import cn.wolfcode.orderServer.service.IOrderService;
import cn.wolfcode.productServer.domain.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
@Slf4j
public class IOrderServiceImpl implements IOrderService {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ProductFeignApi productFeignApi;


    @Override
    public Order get(Long userId, Long productId) {

        log.info("调用订单服务的service层");

        Order order = new Order();
        order.setNumber(1);
        order.setOid(1L);
        order.setUid(userId);
        order.setUsername("默认名称");

        //List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        //int index = new Random().nextInt(instances.size());
        //ServiceInstance instance = instances.get(index);

        //远程调用商品服务，拿到商品数据
       // Product product = restTemplate.getForObject("http://"+instance.getHost()+":"+instance.getPort()+"/get?id="+productId,Product.class);

        //Product product = restTemplate.getForObject("http://product-service/get?id=" + productId, Product.class);

        Product product = productFeignApi.get(productId);

        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());

        return order;
    }
}
